<template>
	<div>
		<!-- 头部 -->
		<login-top middleTop="注册bilibili" isRight>
			<div slot="right" @click="$router.push({name: 'Login'})">登录</div>
		</login-top>
		<!-- 表单 -->
		<van-form @submit="register" @failed="err">
			<login-text 
				v-for="(item,index) in registerForm" 
				:key="index"
				:label="item.label"
				:placeholder="item.placeholder"
				:type="item.type"
				:rules="item.rules"
				:class="item.isMargin ? 'my-15' : ''"
				@input="success($event,item.name)"
			/>
			<login-btn text="注册" />
		</van-form>
	</div>
</template>

<script>
	import { register } from '@/api'
	import LoginTop from '@/components/common/LoginTop.vue'
	import LoginText from '@/components/common/LoginText.vue'
	import LoginBtn from '@/components/common/LoginBtn.vue'
	export default {
		name: 'register',
		data() {
			return {
				// 注册表单域信息数组
				registerForm: [
					{
						name: 'name',
						label: '姓名',
						placeholder: '请输入姓名',
						isMargin: true,
						type: 'text',
						rules: [{pattern:/^[\u4E00-\u9FA5\uf900-\ufa2d·s]{2,20}$/,message: '请输入正确的姓名'}]
					},
					{
						name: 'username',
						label: '账号',
						placeholder: '请输入账号',
						isMargin: false,
						type: 'text',
						rules: [{pattern:/^[0-9a-zA-Z]{6,16}$/,message: '请输入6-16个字符'}]
					},
					{
						name: 'password',
						label: '密码',
						placeholder: '请输入密码',
						isMargin: false,
						type: 'password',
						rules: [{pattern:/^[0-9a-zA-Z]{6,16}$/,message: '请输入6-16个字符'}]
					}
				],
				// 表单数据对象
				formData: {
					name: '',
					username: '',
					password: ''
				}
			}
		},
		components: {
			LoginTop,
			LoginText,
			LoginBtn
		},
		methods: {
			// 自定义事件处理函数
			success(value,key) {
				this.formData[key] = value
			},
			// 注册
			register() {
				// 加载中
				this.$toast.loading({
					message: '加载中...',
					forbidClick: true
				})
				// 发送请求
				register(this.formData)
				.then(({data:res}) => {
					console.log('注册',res)
					// 判断 code
					if (res.code !== 200) return this.$toast.fail(res.msg)
					this.$toast.success(res.msg)
				})
				.catch(err => {
					this.$toast.fail('请求失败，请重新尝试！')
				})
			},
			err(errorInfo) {
				this.$toast.fail('请输入正确格式')
			}
		}
	}
</script>

<style scoped>

</style>